﻿using DevExpress.XtraEditors;
using EkStudio.com.bean.xml.BillModule;
using EkStudio.com.bean.xml.BillReflect;
using EkStudio.com.bean.xml.reflection.JAXB;
using EkStudio.com.bean.xml.RootInterface.Plugin;
using EkStudio.com.bean.xml.Unit;
using EkStudio.com.common.clipboard;
using EkStudio.com.common.unit;
using EkStudio.com.ui.form;
using EkStudio.com.ui.unitbill.property;
using EkStudio.com.ui.unitbill.property.Event;
using EkStudio.Com.UI.Interface;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;

namespace EkStudio.com.ui.unitbill
{
    public partial class BillReflectUnitPanel : XtraUserControl, ProjectUnitBillInterface
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(BillReflectUnitPanel));



        private BillReflectModuleItem module = null;

        private bool readOnly = false;
        private bool save = true;
        private ProjectRootPanel RootPanel = null;
        private List<ProjectUnitBillInterface> SubjectUnit = new List<ProjectUnitBillInterface>();//子面板

        private List<ModuleItem> ModList = new List<ModuleItem>();

        public BillReflectUnitPanel(BillReflectModuleItem bean,ProjectRootPanel Root, bool _readOnly)
        {
            InitializeComponent();
            module = bean;
            RootPanel = Root;
            readOnly = _readOnly;
            InitBillModule();
        }

        private void InitBillModule()
        {
        
            //实例化节点
            if (module.ReflectList == null) module.ReflectList = new BillReflectModuleList();
            if (module.ReflectList.DataNode == null) module.ReflectList.DataNode = new List<BillRefectDataNode>();
            if (module.ReflectList.DataNode.Count > 0)
            {
                for(int i = 0; i < module.ReflectList.DataNode.Count; i++)
                {
                    BillRefectDataNode node = module.ReflectList.DataNode[i];
                    ListViewItem ViewIt = new ListViewItem(node.Caption, 3);
                    ViewIt.Tag = node;
                    FieldsListView.Items.Add(ViewIt);
                }
            }
        }
        #region 常规属性


        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="clazz">复制后的clazz</param>
        /// <returns></returns>
        public bool Copy(out object clazz)
        {
            bool val = false;
            clazz = null;

            return val;
        }

        public string BillKey
        {
            get
            {
                return module.ReflectRoot.Key;
            }
        }

        public bool isSubUnitBill
        {
            get
            {
                return false;
            }
        }

        public ProjectUnitBillInterface ParentPage
        {
            get
            {
                return null;
            }

            set
            {

            }
        }

        public bool ReadOnly
        {
            get
            {
                return readOnly;
            }

            set
            {
                readOnly = value;
            }
        }

        public bool SaveStatus
        {
            get
            {
                return save;
            }

            set
            {
                save = value;
                RootPanel.SaveStatus = value;
            }
        }

        public List<ProjectUnitBillInterface> SubjectPage
        {
            get
            {
                return SubjectUnit;
            }
        }

        public void AddSubjectBill(ProjectUnitBillInterface bill)
        {
            if (!SubjectUnit.Contains(bill))
            {
                SubjectUnit.Add(bill);
            }
        }

        /// <summary>
        /// 判定子页面保存状态
        /// </summary>
        /// <returns></returns>
        private bool isSubSaveStatus()
        {
            bool result = true;
            if (SubjectUnit.Count > 0)
            {
                for (int i = 0; i < SubjectUnit.Count; i++)
                {
                    if (!SubjectUnit[i].SaveStatus)
                    {
                        result = false;
                        break;
                    }
                }
            }

            return result;
        }

        public bool close()
        {
            bool result = true;
            if (!save || !isSubSaveStatus())
            {
                DialogResult dialog = XtraMessageBox.Show("当前数据已更改是否保存?", "提示", MessageBoxButtons.YesNoCancel);
                if (dialog == DialogResult.Yes)
                {
                    saveData(true);
                    result = true;
                }
                else if (dialog == DialogResult.No)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }

            if (result)
            {
                //释放模块占用
                try
                {
                    RootPanel.Http.ReleaseModule(module.ReflectRoot.Key, module.ReflectRoot.Caption, ProjectUtil.TYPE_BILL_REFLECT);
                }
                catch (Exception e)
                {
                    RootPanel.AddConsoleText("页面关闭失败", true);
                    logger.Error("页面关闭失败", e);
                }

            }

            return result;
        }

        public bool ContainSubject(ProjectUnitBillInterface bill)
        {
            return SubjectUnit.Contains(bill);
        }

        public void RemoveSubjectBill(ProjectUnitBillInterface bill)
        {
            if (SubjectUnit.Contains(bill)) SubjectUnit.Remove(bill);
        }

        #endregion

        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="updateParent"></param>
        public void saveData(bool updateParent)
        {
            if (!readOnly && (!save || !isSubSaveStatus()))
            {
                if (!isSubSaveStatus())
                {
                    //先保存子表
                    foreach (ProjectUnitBillInterface subPage in SubjectUnit)
                    {
                        subPage.saveData(false);
                    }
                }
                module.ReflectRoot.RootVersion = BeanUtil.VERSION;
                module.ReflectRoot.LastMender = RootPanel.UserInfo.UserName;
                module.ReflectRoot.LastModified = StringUtility.getZwStandLongDate();
                JAXBContext<BillReflectModuleItem> jaxb = new JAXBContext<BillReflectModuleItem>();

                string xml = jaxb.marshal(module, true);

                string result = RootPanel.Http.SaveXmlBean(module.ReflectRoot.Key, ProjectUtil.TYPE_BILL_REFLECT, xml);

                XmlDocument docXml = new XmlDocument();
                try
                {
                    docXml.LoadXml(result);
                    XmlElement root = docXml.DocumentElement;
                    XmlNode node = root.SelectSingleNode("result");
                    if (node.InnerText == "0")
                    {
                        RootPanel.AddConsoleText(string.Format("保存模块[{0}]成功", module.ReflectRoot.Caption), false);
                    }
                    else
                    {
                        RootPanel.AddConsoleText(string.Format("保存模块[{0}]失败", module.ReflectRoot.Caption), false);
                    }
                }
                catch (Exception e)
                {
                    RootPanel.AddConsoleText(string.Format("保存模块[{0}]失败", module.ReflectRoot.Caption), false);
                    logger.Error("保存失败", e);
                }
            }
            save = true;
            if (updateParent) RootPanel.SaveStatus = true;
            //ModulePropertyList.Refresh();
        }
        /// <summary>
        /// 字段集change事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FieldsListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            PManTabControl.SelectedIndex = 0;

            if (FieldsListView.SelectedItems.Count > 1)//多选
            {
                BillReflectNodeToProperty[] dataList = new BillReflectNodeToProperty[FieldsListView.SelectedItems.Count];
                for(int i = 0; i < FieldsListView.SelectedItems.Count; i++)
                {
                    BillRefectDataNode node = FieldsListView.SelectedItems[i].Tag as BillRefectDataNode;
                    BillReflectNodeToProperty data = new BillReflectNodeToProperty(node, module);
                    dataList[i] = data;
                }
                BillReflectNodeToProperty dataNode = new BillReflectNodeToProperty(dataList, module);
                NodePropertyGrid.SelectedObject = dataNode;
                NodePropertyGrid.Visible = true;
            }
            else if(FieldsListView.SelectedItems.Count == 1)
            {
                BillRefectDataNode node = FieldsListView.SelectedItems[0].Tag as BillRefectDataNode;
                if (node != null)
                {
                    BillReflectNodeToProperty data = new BillReflectNodeToProperty(node, module);
                    NodePropertyGrid.SelectedObject = data;
                    NodePropertyGrid.Visible = true;
                }
            }
            else
            {
                NodePropertyGrid.Visible = false;
            }
        }

        private void FieldsListView_Click(object sender, EventArgs e)
        {
            FieldsListView_SelectedIndexChanged(sender, e);
        }

        private void FieldsListView_MouseClick(object sender, MouseEventArgs e)
        {
            if (FieldsListView.SelectedItems.Count == 0)
            {
                NodePropertyGrid.Visible = false;
            }
        }

        #region 菜单功能区域
        private void FieldPopNewNode_Click(object sender, EventArgs e)//新建
        {
            BillRefectDataNode data = new BillRefectDataNode();
            ListViewItem it = new ListViewItem(data.Caption, 3);
            it.Tag = data;
            module.ReflectList.DataNode.Add(data);
            FieldsListView.Items.Add(it);
            SaveStatus = false;
        }
        
        private void FieldPopDeleteNode_Click(object sender, EventArgs e)//删除
        {
            if(FieldsListView.SelectedItems.Count == 1)
            {
                ListViewItem it = FieldsListView.SelectedItems[0];
                BillRefectDataNode data = it.Tag as BillRefectDataNode;
                if (module.ReflectList.DataNode.Contains(data))
                {
                    module.ReflectList.DataNode.Remove(data);
                    FieldsListView.Items.Remove(it);
                    SaveStatus = false;
                }
            }
        }
        /// <summary>
        /// 复制功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FieldPopCopyNode_Click(object sender, EventArgs e)
        {
            if (FieldsListView.SelectedItems.Count > 0)
            {
                BillRefectDataNode[] nodes = new BillRefectDataNode[FieldsListView.SelectedItems.Count];
                int i = 0;
                foreach (ListViewItem it in FieldsListView.SelectedItems)
                {
                    BillRefectDataNode data = it.Tag as BillRefectDataNode;
                    BillRefectDataNode clone = data.Clone() as BillRefectDataNode;
                    nodes[i] = clone;
                    i++;
                }
                JClipboard.copy(nodes);
            }
        }
        /// <summary>
        /// 粘贴功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FieldPopPasteNode_Click(object sender, EventArgs e)
        {
            RootPanel.AddConsoleText(string.Format("只读:{0}存在数据{1}",Convert.ToString(readOnly),Convert.ToString(JClipboard.ContainData())), false);
            if (readOnly) return;
            if (!JClipboard.ContainData()) return;
            
            if(JClipboard.Paste()[0] is BillRefectDataNode)
            {
                foreach (BillRefectDataNode node in JClipboard.Paste())
                {
                    if (node != null)
                    {
                        ListViewItem it = new ListViewItem(node.Caption, 1);
                        it.Tag = node;
                        FieldsListView.Items.Add(it);
                        module.ReflectList.DataNode.Add(node);
                    }
                }
                SaveStatus = false;
                JClipboard.Clear();
            }
            
        }


        #endregion

        private void NodePropertyGrid_CellValueChanged(object sender, DevExpress.XtraVerticalGrid.Events.CellValueChangedEventArgs e)
        {
            if(e.Row.Properties.FieldName == "Caption")
            {
                if(FieldsListView.SelectedItems.Count == 1)
                {
                    ListViewItem it = FieldsListView.SelectedItems[0];
                    it.Text = Convert.ToString(e.Value);
                }
            }
            SaveStatus = false;
        }
        /// <summary>
        /// 数据库编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NodeRepositoryAutoSourceEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            BillReflectNodeToProperty ToProperty = NodePropertyGrid.SelectedObject as BillReflectNodeToProperty;
            if (ToProperty != null)
            {
                BillRefectDataNode node = ToProperty.DataNode;
                if (node != null)
                {
                    ReflectAutoSourceForm form = new ReflectAutoSourceForm(module, RootPanel, this, node, ToProperty.Target);
                    if(form.ShowDialog() == DialogResult.OK)
                    {
                        NodePropertyGrid.Refresh();
                        SaveStatus = false;
                    }
                }
            }
        }
        /// <summary>
        /// 目标选择控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NodeRepositoryButTarget_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                BillReflectNodeToProperty ToProperty = NodePropertyGrid.SelectedObject as BillReflectNodeToProperty;
                if (ToProperty != null && !ToProperty.IsMultiple())
                {
                    BillRefectDataNode node = ToProperty.DataNode;
                    if (node != null)
                    {
                        ModuleSheetSelectForm form = new ModuleSheetSelectForm(node.TargetKey, RootPanel, readOnly);
                        if(form.ShowDialog() == DialogResult.OK)
                        {
                            node.TargetKey = form.OutModKey;
                            node.TargetCaption = form.OutModCaption;
                            ToProperty.Target = form.OutModule;
                            NodePropertyGrid.Refresh();
                            SaveStatus = false;
                        }
                    }
                }
            }
            else if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                BillReflectNodeToProperty ToProperty = NodePropertyGrid.SelectedObject as BillReflectNodeToProperty;
                if (ToProperty != null && !ToProperty.IsMultiple())
                {
                    BillRefectDataNode node = ToProperty.DataNode;
                    if (node != null)
                    {
                        if (XtraMessageBox.Show("您确认清除已选定的模块吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            node.TargetKey = "";
                            node.TargetCaption = "";
                            NodePropertyGrid.Refresh();
                            SaveStatus = false;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 数据源模块选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NodeRepositoryReflectBut_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                BillReflectNodeToProperty ToProperty = NodePropertyGrid.SelectedObject as BillReflectNodeToProperty;
                if (ToProperty != null && !ToProperty.IsMultiple())
                {
                    BillRefectDataNode node = ToProperty.DataNode;
                    if (node != null)
                    {
                        ModuleSheetSelectForm form = new ModuleSheetSelectForm(node.RefectKey, RootPanel, readOnly);
                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            node.RefectKey = form.OutModKey;
                            node.RefectCaption = form.OutModCaption;
                            NodePropertyGrid.Refresh();
                            SaveStatus = false;
                        }
                    }
                }
            }
            else if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                BillReflectNodeToProperty ToProperty = NodePropertyGrid.SelectedObject as BillReflectNodeToProperty;
                if (ToProperty != null && !ToProperty.IsMultiple())
                {
                    BillRefectDataNode node = ToProperty.DataNode;
                    if (node != null)
                    {
                        if (XtraMessageBox.Show("您确认清除已选定的模块吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            node.RefectKey = "";
                            node.RefectCaption = "";
                            NodePropertyGrid.Refresh();
                            SaveStatus = false;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 扩展代码编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NodeRepositoryJavaButEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            BillReflectNodeToProperty ToProperty = NodePropertyGrid.SelectedObject as BillReflectNodeToProperty;
            if (module.ExpandCode == null) module.ExpandCode = new BillExpandCodeRoot();
            if (module.ExpandCode.JavaPlugin == null) module.ExpandCode.JavaPlugin = new BillExpandJavaCodeRoot();
            if (module.ExpandCode.JavaPlugin.JavaItem == null) module.ExpandCode.JavaPlugin.JavaItem = new List<BillExpandJavaCodeItem>();

            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                if (ToProperty != null && !ToProperty.IsMultiple())
                {
                    bool save = true;
                    BillExpandJavaCodeItem java = ToProperty.getJavaCode();
                    if (java == null)
                    {
                        java = new BillExpandJavaCodeItem();
                        java.Key = "ClazzReflect_" + ToProperty.Key + "_Plugin";
                        java.JavaPackage = "com.kootop.plugin." + module.ReflectRoot.JavaPackage;
                        java.Caption = module.ReflectRoot.Caption + "->" + ToProperty.Caption + "的扩展代码";
                        java.Bind = ToProperty.Key;
                        java.Content = BeanUtil.getReflectJavaCode(java.Key, java.JavaPackage);
                        module.ExpandCode.JavaPlugin.JavaItem.Add(java);
                        save = false;
                        NodePropertyGrid.Refresh();
                        SaveStatus = false;
                    }
                    BillReflectJPluginPanel panel = new BillReflectJPluginPanel(RootPanel, this, java, save);
                    panel.Dock = DockStyle.Fill;
                    AddSubjectBill(panel);
                    RootPanel.AddTabPage(java.Caption, panel, 7);
                }
            }
            else if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)//删除
            {
                if(ToProperty !=null && !ToProperty.IsMultiple() && ToProperty.getJavaCode() != null)
                {
                    if (XtraMessageBox.Show("您确认删除当前反射配置的扩展代码吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        module.ExpandCode.JavaPlugin.JavaItem.Clear();
                        NodePropertyGrid.Refresh();
                        SaveStatus = false;
                    }
                        
                }
            }
            
            
        }

        private void FieldPopCheckAllNode_Click(object sender, EventArgs e)
        {
            
        }
    }

    class ModuleItem
    {
        private string caption = "";
        private string modName = "";

        public ModuleItem(string cap,string key)
        {
            caption = cap;
            modName = key;
        }

        public string Caption
        {
            get { return caption; }
            set { caption = value; }
        }

        public string ModName
        {
            get { return modName; }
            set { modName = value; }
        }

        public override string ToString()
        {
            return Caption;
        }
    }
}
